﻿using System;
using System.Collections.Generic;
using Cinemachine;
using DoDoveFramework;
using Script;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.Tilemaps;
using Screen = UnityEngine.Device.Screen;

namespace DoDove
{
    public interface ICameraHandler
    {
        public string GetCameraName();
        public void RegisterCameraHandler();
        public GameObject GetCameraObject();
        public CinemachineVirtualCamera GetVirtualCamera();
        public void MoveToCenter();
        public void MoveTargetObj();
    }

    public class CameraManager : Singleton<CameraManager>
    {
        public Transform _cameraRoot;

        //缓存对应相机ID
        private Dictionary<string, ICameraHandler> _cameras = new Dictionary<string, ICameraHandler>();
        private ICameraHandler _curCamera;

        protected override void Initialize()
        {
            //初始化相机节点 // 需要持久化的节点才放在这
            _cameraRoot = GameObject.Find("VirtualCameraRoot")?.transform;
            if (_cameraRoot == null)
            {
                var poolRoot = new GameObject("VirtualCameraRoot");
                poolRoot.transform.SetParent(GameBoot.Instance.transform);
                poolRoot.transform.localPosition = Vector3.zero;
                _cameraRoot = poolRoot.transform;
            }
        }

        public void SwitchCamera<T>(string cameraName) where T : ICameraHandler,new()
        {
            if (!_cameras.ContainsKey(cameraName))
            {
                var camera = new T();
                _cameras[cameraName] = camera;
            }
            
            if (_curCamera != null)
            {
                _curCamera.GetVirtualCamera().Priority = 0;
            }
            _curCamera = _cameras[cameraName];
            _curCamera.GetVirtualCamera().Priority = 10;
        }

        public void RegisterVirtualCamera(ICameraHandler virtualCamera)
        {
            var gameObject = virtualCamera.GetCameraObject();
            gameObject.transform.SetParent(_cameraRoot);
            gameObject.transform.localPosition = Vector3.zero;
            _cameras[virtualCamera.GetCameraName()] = virtualCamera;
        }

        public void MoveTargetObj()
        {
            _curCamera?.MoveTargetObj();
        }

        public void MoveToCenter()
        {
            _curCamera?.MoveToCenter();
        }

        public void DestroyVirtualCamera(ICameraHandler virtualCamera)
        {
            _cameras[virtualCamera.GetCameraName()] = null;
            GameObject.Destroy(_cameraRoot);
        }
    }
}